from typing import AsyncGenerator

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session

from app.core.config import settings
from app.utils.logger import logger

engine = create_engine(
    settings.SQLALCHEMY_DATABASE_URI,
    echo=settings.DB_ECHO,
    pool_size=settings.DB_POOL_SIZE,  # 连接池中保持的最大连接数。
    max_overflow=settings.DB_MAX_OVERFLOW,  # 允许超出连接池大小的额外连接数。
    pool_recycle=settings.DB_POOL_RECYCLE,  # 连接自动回收的时间间隔（秒），防止连接超时。
    pool_pre_ping=settings.DB_POOL_PRE_PING,  # 是否在每次获取连接前检查连接的有效性。
)
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)


async def get_db() -> AsyncGenerator[Session, None]:
    logger.info("getting database session")
    db = SessionLocal()
    try:
        yield db
    except Exception as e:
        db.rollback()
        logger.exception(f"session execution error: {str(e)}")
        raise
    finally:
        logger.info("close database session")
        db.close()

# from collections.abc import Generator
# from sqlmodel import Session
# def get_session() -> Generator[Session, None, None]:
#     session = Session(engine)
#     try:
#         yield session
#     finally:
#         session.close()
